package myaction.student;

import myutil.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class StudentLoginAction extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sql = "select * from t_students where s_username=? and s_password=?";
        try {
            Connection conn = DbUtil.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                String student_id = rs.getString(1);
                String student_name = rs.getString(4);
                HttpSession session = request.getSession();
                session.setAttribute("student_id", student_id);
                session.setAttribute("student_name", student_name);
                request.getRequestDispatcher("student/studentmain.jsp").forward(request, response);
            } else {
                request.setAttribute("mess", "用户名或密码错误，请重新输入！");
//                request.setAttribute("mess", "<script> alert('用户名或密码错误，请重新输入！');</script>");
                request.getRequestDispatcher("student/studentlogin.jsp").forward(request, response);
            }
            rs.close();
            ps.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

